//rock.zhang.cn@gmail.com

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <linux/limits.h>

#define BUF_LEN	 (1024)

/* 
 * 用法：filename　表示欲在可执行程序中包含的已经编译的文件。
 * ./compose filename
 * 生成 filename.h 中包含filename的文件字符串.
 * 生成的filename.h　供release程序使用，release程序将些字符串重新写回成文件.
 */
int main(int argc, char ** argv)
{
	if(argc != 2)
	{
		printf("Usage : compose FileName\n");
		return -1;
	}

	FILE * srcFile= NULL;

	if((srcFile=fopen(argv[1],"rb"))==NULL)
	{
		printf("Cannot open file strike any key exit!");
		exit(1);
	}

	unsigned char readBuf[BUF_LEN] = {0};
	char writeBuf[BUF_LEN] = {0};

	char headerFile[PATH_MAX];
	strncpy(headerFile, argv[1], PATH_MAX);
	headerFile[strlen(argv[1])] = '.';
	headerFile[strlen(argv[1])+ 1] = 'h';
	headerFile[strlen(argv[1])+ 2] = '\0';
	
	FILE * headerFp = NULL;
	if((headerFp = fopen(headerFile,"w"))==NULL)
	{
		printf("Cannot open file strike any key exit!");
		exit(1);
	}

    //write declaration part.
	snprintf(writeBuf, BUF_LEN, "\nconst unsigned char %s[] = { \n\t\t", "variableName"); 
	fputs(writeBuf, headerFp);

    //write actual data part.
	int  readCnt = 0;
	while(readCnt = fread(readBuf, sizeof(char), BUF_LEN, srcFile))
	{
		for(int i = 0; i < readCnt; i++)
		{
			snprintf(writeBuf, BUF_LEN, "0x%x, ", readBuf[i]);
			fputs(writeBuf, headerFp);

			if((i+1)%10 == 0)
			{
				fputs("\n\t\t", headerFp);
			}
		}
	}

    //write data end part.
	fputs("\n", headerFp);
	fputs("\t};\n", headerFp);

	fclose(srcFile);
	fclose(headerFp);

	return 0;
}
